<template>
  <div>
    <!-- 返回按钮 -->
    <div class="back-button">
      <el-button type="text" @click="goBack" icon="el-icon-arrow-left">
        返回
      </el-button>
    </div>
    <el-row :gutter="20">
      <el-col :span="3">
        <el-avatar :size="100" :src="$store.getters.avatar"></el-avatar>
      </el-col>
      <el-col :span="12">
        <h2>{{ name }}</h2>
      </el-col>
    </el-row>
    <el-tabs v-model="activeTab">
      <el-tab-pane label="我的帖子" name="posts">
        <router-view @updateTotal="handleUpdateTotal"></router-view>
      </el-tab-pane>
      <el-tab-pane label="我的评论" name="comments">
        <router-view></router-view>
      </el-tab-pane>
      <el-tab-pane label="我的关注" name="following">
        <router-view></router-view>
      </el-tab-pane>
      <el-tab-pane label="我的收藏" name="likes">
        <router-view></router-view>
      </el-tab-pane>
    </el-tabs>

  </div>
</template>

<script>
import { getPostsByUser } from '@/api/forum/posts'
import { getInfo } from '@/api/login'

export default {
  name: 'UserProfile',
  mounted () {
    this.getPersonInfo()
  },
  data () {
    return {
      activeTab: this.$route.params.tab || 'posts',  // 初始化为当前路由参数或默认值 id来自URL
      userId: this.$route.params.userId,   // 用户 id 来自 url
      queryParams: {
        pageNum: 1, // 当前页码
        pageSize: 8, // 每页显示条数
        title: null,
        userId: null,
        name: null,
        content: null,
        createdAt: null,
        likes: null,
        comments: null,
        status: null,
        updatedAt: null,
        imageUrl: null,
        viewCount: null,
        categoryName: null,
      },
      name: null,
      total: 0, // 总数据量
      loading: false, //遮罩层
      postsList: [], // 数据列表
    }
  },
  methods: {
    handleUpdateTotal (newTotal) {
      this.total = newTotal
    },
    // 查询个人id 名字
    getPersonInfo () {
      getInfo().then(response => {
        this.name = response.user.nickName
      }).catch(error => {
        console.error('获取用户信息失败', error)
      })
    },
    // 返回上一页
    goBack() {
        this.$router.push({ name: 'first' }).catch(err => {
          if (err.name === 'NavigationDuplicated') {
            console.log('重复导航被忽略');
            return;
          }
          throw err;
        });
      }
    },
  watch: {
    activeTab (newTab) {
      // 当 activeTab 改变时，更新路由到嵌套路由
      if (this.$route.params.tab !== newTab) {
        this.$router.push(`/first/UserProfile/${this.userId}/${newTab}/${newTab}`).catch(() => {
        })
      }
    },
    '$route' (to) {
      // 当路由改变时，更新 activeTab 和 userId
      if (to.params.tab !== this.activeTab) {
        this.activeTab = to.params.tab || 'posts'
      }
      if (to.params.userId !== this.userId) {
        this.userId = to.params.userId
      }
    },
  }
}
</script>

<style scoped>
/* 添加一些样式 */
</style>
